<template>
  <el-dialog
    v-model="visible"
    title="批量分配到业务员"
    width="980px"
    align-center
    :close-on-click-modal="false"
    destroy-on-close
    draggable
    class="assign-sales-dialog"
    @close="handleClose"
  >
    <!-- 订单列表 - 卡片化 -->
    <div class="orders-card">
      <div class="card-header">
        <h3>待分配订单（{{ orders.length }}）</h3>
        <el-tag v-if="orders.length" type="info" size="small" round>{{ orders.length }} 条</el-tag>
      </div>

      <el-table
        v-if="orders.length"
        :data="orders"
        border
        class="order-table"
        row-key="orderId"
        :height="orders.length > 2 ? 240 : 'auto'"
        style="border-radius: 12px; overflow: hidden"
      >
        <el-table-column type="index" width="50" label="#" align="center" />
        <el-table-column prop="orderNo" label="订单号" min-width="160" show-overflow-tooltip />
        <el-table-column prop="receiverName" label="客户姓名" width="120" />
        <el-table-column prop="receiverPhone" label="电话" width="140" />
        <el-table-column
          prop="receiverAddress"
          label="收货地址"
          min-width="200"
          show-overflow-tooltip
        />
      </el-table>

      <template v-else>
        <div class="empty-state">
          <el-icon size="32" color="#a8a8a8"><DocumentRemove /></el-icon>
          <p class="empty-text">暂无待分配订单</p>
        </div>
      </template>
    </div>

    <!-- 表单区域 - 内嵌优雅 -->
    <div class="form-section">
      <el-form ref="formRef" :model="form" :rules="rules" label-position="left" label-width="80px">
        <el-form-item label="业务员" prop="issuer">
          <el-select
            v-model="form.issuer"
            placeholder="请选择业务员"
            filterable
            class="sales-select"
            popper-class="sales-select-popper"
          >
            <el-option
              v-for="u in users"
              :key="u.userId"
              :label="`${u.nickName}(${u.phonenumber})`"
              :value="u.userId"
            >
              <div class="option-item">
                <el-avatar :size="26" :style="{ backgroundColor: '#409EFF', color: '#fff' }">
                  {{ u.nickName?.slice(0, 1).toUpperCase() }}
                </el-avatar>
                <div class="option-info">
                  <div class="name">{{ u.nickName }}</div>
                  <div class="phone">{{ u.phonenumber }}</div>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <!-- 页脚按钮 - 渐变+微动效 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" size="large">取消</el-button>
        <el-button
          type="primary"
          size="large"
          :loading="submitting"
          :disabled="!form.issuer || !orders.length"
          @click="handleConfirm"
          class="btn-confirm"
        >
          批量分配
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
// ... (保持原有 script 逻辑不变)
import { ref, reactive, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { DocumentRemove } from '@element-plus/icons-vue';
import { assignOrderToSalesman } from '../../api/platformOrders/orders/list';
import { applyRemarks } from '../../utils/order';
import { cloneDeep } from 'lodash';
import useUserStore from '../../store/modules/user';
import { updateCustomerSalesman } from '../../api/customers';

defineProps({ users: Array });

const visible = ref(false);
const submitting = ref(false);
const orders = ref([]);
const userApp = useUserStore();

const emit = defineEmits(['ok']);

const form = reactive({ issuer: '' });
const rules = {
  issuer: [{ required: true, message: '请选择业务员', trigger: 'change' }]
};

const formRef = ref();

function show(list) {
  const deep = cloneDeep(list || []);
  applyRemarks(deep, userApp.printStr);
  orders.value = deep;
  form.issuer = '';
  visible.value = true;
  nextTick(() => formRef.value?.clearValidate());
}

function handleClose() {
  visible.value = false;
  submitting.value = false;
}

async function handleConfirm() {
  if (!orders.value.length) {
    return ElMessage.warning('请先选择订单');
  }

  const valid = await formRef.value?.validate().catch(() => false);
  if (!valid) return;

  submitting.value = true;

  try {
    const uniqueIds = Array.from(new Set(orders.value.map((v) => v.customerId)));
    const tasks = uniqueIds.map((id) =>
      updateCustomerSalesman({
        customerId: id,
        salesmanId: form.issuer
      })
    );

    const results = await Promise.allSettled(tasks);
    const success = results.filter((r) => r.status === 'fulfilled').length;
    const failed = results.length - success;

    if (failed === 0) {
      ElMessage.success(`成功分配 ${success} 个客户`);
      emit('ok');
      handleClose();
    } else {
      ElMessage.error(`成功 ${success} 个，失败 ${failed} 个，请检查日志`);
    }
  } catch (err) {
    ElMessage.error('批量分配发生异常，请稍后重试');
  } finally {
    submitting.value = false;
  }
}

defineExpose({ show });
</script>

<style lang="scss" scoped>
.assign-sales-dialog {
  :deep(.el-dialog__header) {
    padding: 24px 28px 16px;
    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #1f2329;
    }
  }

  :deep(.el-dialog__body) {
    padding: 0 28px 24px;
  }
}

.orders-card {
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
  padding: 20px;
  margin-bottom: 24px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h3 {
      font-size: 15px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }
  }

  .order-table {
    border: none;
    border-radius: 12px;
    overflow: hidden;

    :deep(.el-table__header th) {
      background-color: #fafafa;
      color: #555;
      font-weight: 500;
    }

    :deep(.el-table__row) {
      &:hover {
        background-color: #f9fbff;
      }
    }

    :deep(.cell) {
      padding: 10px 12px;
    }
  }

  .empty-state {
    text-align: center;
    padding: 40px 0;
    color: #999;
    .empty-text {
      margin-top: 12px;
      font-size: 14px;
    }
  }
}

.form-section {
  background: #f8fafc;
  border-radius: 14px;
  padding: 20px;
  border: 1px solid #edf2f7;

  .el-form-item {
    margin-bottom: 0;
  }

  .sales-select {
    width: 100%;
  }
}

.option-item {
  display: flex;
  align-items: center;
  gap: 12px;
  .option-info {
    line-height: 1.4;
    .name {
      font-weight: 500;
      color: #333;
    }
    .phone {
      font-size: 12px;
      color: #888;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding-top: 8px;

  .el-button {
    width: 120px;
    border-radius: 8px;
    font-weight: 500;
  }

  .btn-confirm {
    background: linear-gradient(135deg, #409eff, #2a7fff);
    border: none;
    color: white;
    transition: all 0.2s ease;

    &:hover:not(:disabled) {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
    }

    &:active {
      transform: translateY(0);
    }
  }
}

// 自定义下拉弹窗样式
:deep(.sales-select-popper) {
  border-radius: 12px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}
</style>
